package com.runshu.runshuwulian.base.net;


import com.hyphenate.easeui.mwidget.mutil.MUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitFactory {

    private final ApiService mApiService;

    private static RetrofitFactory mRetrofitFactory;

    private RetrofitFactory() {
        //创建日志拦截器
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel( HttpLoggingInterceptor.Level.BODY );//设定日志级别
        //创建OkHttpClient
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout( ApiService.HTTP_TIME, TimeUnit.SECONDS )
                .readTimeout( ApiService.HTTP_TIME, TimeUnit.SECONDS )
                .writeTimeout( ApiService.HTTP_TIME, TimeUnit.SECONDS )
                .addInterceptor( getInterceptor() )
                .addInterceptor( new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request();
                        if (request.method().equals( "POST" )) {
                            if (request.body() instanceof FormBody) {
                                FormBody.Builder bodyBuilder = new FormBody.Builder();
                                FormBody formBody = (FormBody) request.body();
                                //把原来的参数添加到新的构造器，（因为没找到直接添加，所以就new新的）
                                for (int i = 0; i < formBody.size(); i++) {
                                    bodyBuilder.addEncoded( formBody.encodedName( i ), formBody.encodedValue( i ) );
                                }
                                String value = String.valueOf( System.currentTimeMillis() / 1000 );
                                formBody = bodyBuilder
                                        .addEncoded( "time", value )
                                        .addEncoded( "device", "WECHAT-OAUTH-OPENID-DEVICE-NUMBER" )
                                        .addEncoded( "from", "3" )
                                        .addEncoded( "user_type", "0" )
                                        .addEncoded( "version", "1.0" )
//                                        .addEncoded( "version", "1.0" )
                                        .addEncoded( "signature", MUtils.Md5("time=" + value + "&device=WECHAT-OAUTH-OPENID-DEVICE-NUMBER&version=1.0"
                                                + "&key=8bd1f3df57276029fd7efc36ad5f8819"))
                                        .build();
                                request = request.newBuilder().post( formBody ).build();
                            }
                        }
                        return chain.proceed( request );
                    }
                } ).addInterceptor( httpLoggingInterceptor ).build();//添加拦截器

        //创建Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl( ApiService.Host )
                .addConverterFactory( GsonConverterFactory.create() )//添加gson转换器
                .addCallAdapterFactory( RxJava2CallAdapterFactory.create() )//添加rxjava2转换器
                .client( mOkHttpClient )
                .build();

        //创建接口实现类
        mApiService = retrofit.create( ApiService.class );

    }

    private Interceptor getInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //获取request
                Request request = chain.request();
                //获取request的创建者builder
                Request.Builder builder = request.newBuilder();
                //从request中获取headers，通过给定的键url_name
                List<String> headerValues = request.headers( "url_host" );
                if (headerValues != null && headerValues.size() > 0) {
                    //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
                    builder.removeHeader( "url_host" );

                    //匹配获得新的BaseUrl
                    String headerValue = headerValues.get( 0 );
                    HttpUrl newBaseUrl = null;
                    if ("user".equals( headerValue )) {
                        newBaseUrl = HttpUrl.parse( ApiService.Host );
                    } else if ("pay".equals( headerValue )) {
//                                newBaseUrl = HttpUrl.parse(BASE_URL_PAY);
                    } else if ("login".equals( headerValue )) {
                        newBaseUrl = HttpUrl.parse( ApiService.LoginHost );
                    } else {
                        newBaseUrl = HttpUrl.parse( ApiService.Host );
                    }

                    //从request中获取原有的HttpUrl实例oldHttpUrl
                    HttpUrl oldHttpUrl = request.url();
                    //重建新的HttpUrl，修改需要修改的url部分
                    HttpUrl newFullUrl = oldHttpUrl
                            .newBuilder()
                            .scheme( newBaseUrl.scheme() )
                            .host( newBaseUrl.host() )
                            .port( newBaseUrl.port() )
                            .build();

                    //重建这个request，通过builder.url(newFullUrl).build()；
                    //然后返回一个response至此结束修改
                    return chain.proceed( builder.url( newFullUrl ).build() );
                } else {
                    return chain.proceed( request );
                }
            }
        };
    }

    // 懒汉式单例模式
    public static RetrofitFactory getInstence() {
        if (mRetrofitFactory == null) {
            // 静态方法，使用当前类本身充当进程锁
            synchronized (RetrofitFactory.class) {
                if (mRetrofitFactory == null)
                    mRetrofitFactory = new RetrofitFactory();
            }
        }
        return mRetrofitFactory;
    }

    //请求网络的API接口类
    public ApiService API() {
        return mApiService;
    }

    public static ObservableTransformer threadTransformer() {
        return new ObservableTransformer() {
            @Override
            public ObservableSource apply(Observable observable) {
                return observable
                        .subscribeOn( Schedulers.io() )
                        .unsubscribeOn( Schedulers.io() )
                        .observeOn( AndroidSchedulers.mainThread() );
            }
        };
    }
}
